<template>
  <div class="flow-wrap">
    <base-modal
      :title="title"
      width="676px"
      @cancel="closeDialog"
      :show.sync="isShow"
      :mask-closeable="false">


      <div class="add-form">
        <div class="form-step">
          <div class="step-item">
            <i class="el-icon-remove-outline start-state"></i>
            <span>{{ $t('projectManage.setting.flowSetting.startState') }}</span>
          </div>
          <div class="middle-line">
            <img :src="arrowStep" alt="">
          </div>
          <div class="step-item item-middle">
            <span>{{ $t('common.base.operation') }}</span>
          </div>
          <div class="middle-line">
            <img :src="arrowStep" alt="">
          </div>
          <div class="step-item">
            <i class="el-icon-time target-state"></i>
            <span>{{ $t('projectManage.setting.flowSetting.targetState') }}</span>
          </div>
        </div>
        <el-form label-position="top" :model="form" :rules="rules" ref="flowForm" >
          <el-form-item :label="$t('projectManage.setting.flowSetting.conversionName')" prop="convertName">
            <el-input class="w-360" maxlength="10" v-model.trim="form.convertName" :placeholder="$t('projectManage.setting.flowSetting.placeholder1')" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.flowSetting.startState')" prop="sourceStatusId">
            <el-select class="w-100" clearable v-model="form.sourceStatusId" :placeholder="$t('projectManage.setting.flowSetting.placeholder2')">
              <el-option
                v-for="item in statusListComput('targetStatusId')"
                :key="item.id"
                :label="item.projectStatusName"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('projectManage.setting.flowSetting.targetState')" prop="targetStatusId">
            <el-select class="w-100" clearable v-model="form.targetStatusId" :placeholder="$t('projectManage.setting.flowSetting.placeholder4')">
              <el-option
                v-for="item in statusListComput('sourceStatusId')"
                :key="item.id"
                :label="item.projectStatusName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('projectManage.setting.flowSetting.moveRule')" prop="moveRule">
            <el-select multiple :multiple-limit="10" class="w-100" v-model="form.rule" :placeholder="$t('projectManage.setting.flowSetting.placeholder3')">
              <el-option
                v-for="item in taskList"
                :key="item.id"
                :label="item.projectTaskName"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('projectManage.setting.flowSetting.approveRule')" prop="approveType">
            <el-radio-group v-model="form.approveType" @change="switchLevel">
              <el-radio :label="1">{{$t('task.setting.taskTypeSetting.flow.components.noApprove')}}</el-radio>
              <el-radio :label="4" class="ml-12">{{$t('common.base.heightApproveLevel')}}</el-radio>
            </el-radio-group>

            <template v-if="form.approveType === 4">
              <div class="approve-btn">
                <el-button type="primary" @click="switchLevel(4)">{{$t('common.zhongqi.setApprove')}}</el-button>
              </div>
            </template>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="closeDialog">{{$t('common.base.cancel')}}</el-button>
        <el-button :loading="pedding" type="primary" @click="submitForm">{{$t('common.base.makeSure')}}</el-button>
      </div>
    </base-modal>
    <base-modal
      :allowFullscreen="true"
        :title="$t('common.zhongqi.setApprovalProcess')"
        size="large"
        width="800px"
        height="600px"
        :sizeData="{ minWidth: 1060, minHeight: 650 }"
        :show.sync="heightApproveLevelDia"
        >
        <div v-if="heightApproveLevelDia" class="paas-wrap" v-loading="editloadingShow">
          <iframe :key="iframekey" id="frame_heightApprove" ref="iframePageEdit" :src="iframeEditUrl" height="100%" width="100%" @load="editloadingShow = false"/>
        </div>
        <span slot="footer" class="dialog-footer">
            <el-button @click="heightApproveLevelDia = false">{{$t('common.base.cancel')}}</el-button>
            <el-button :disabled="pending" type="primary" @click="savePaasResult">{{ $t('common.base.makeSure') }}</el-button>
        </span>
    </base-modal>
  </div>
</template>
<script>

import arrowStep from '@src/assets/img/arrow.png';
import _ from 'lodash';
import { reDeployment, updateProcess } from '@src/api/TaskApi.ts';
import * as ProjectManage from '@src/api/ProjectManage.ts';
const CreateUuid = () => URL.createObjectURL(new Blob()).substr(-36);

export default {
  name: 'create-flow',
  data() {
    return {
      arrowStep,
      compId: CreateUuid(),
      title: this.$t('projectManage.setting.flowSetting.flowTitle'),
      heightApproveLevelDia: false,
      editloadingShow: false,
      iframekey: new Date().getTime(),
      pending: false,
      iframeEditUrl: '',
      form: {
        convertName: '',
        sourceStatusId: '',  
        sourceColor: '', // 起始状态的颜色值
        targetStatusId: '',
        targetColor: '', // 目标状态的颜色值
        rule:'',
        approveType: 1, // 1 无需审批 4 高级审批 默认是无需审批
      },
      rules: {
        convertName: [
          { required: true, message: this.$t('projectManage.setting.flowSetting.placeholder1'), trigger: 'blur' },
          { max: 10, message: this.$t('projectManage.setting.projectStatus.ruleMess1'), trigger: 'blur' }
        ],
        sourceStatusId: [
          { required: true, message: this.$t('projectManage.setting.flowSetting.placeholder2'), trigger: 'change' }
        ],
        targetStatusId: [
          { required: true, message: this.$t('projectManage.setting.flowSetting.placeholder4'), trigger: 'change' }
        ],
        rule: [
          { required: true, message: this.$t('projectManage.setting.flowSetting.placeholder3'), trigger: 'change' }
        ],
        approveType: [
          { required: true, message: '', trigger: 'change' }
        ],
      },
      pedding: false,
      isShow: false,
      isFormEdit: false,
      approveJson: {},
      approveSetting: {},
      statusList: [],
      taskList: [],
    }
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
  },
  mounted() {
    let that = this
    // 高级审批灰度 如果弹窗是打开的话，监听数据
    function onMessageCall(event) {
      const { data, action, compId } = event.data
      // 判断是否是当前组件发起的请求
      if (compId !== that.compId) { return }
      if(action === 'PaaS.frame.returnPaaSWorkflow') {
        const { flowData, currentVersion, nodeStyle } = _.cloneDeep(data)
        that.approveJson = flowData
        let params = {
          nodeStyle,
          antvJson: that.approveJson || {},
          workflowTemplateId: currentVersion?.bizId || '',
          ...that.approveSetting
        }

        // 接受paas传过来的参数保存审批数据
        updateProcess(params).then((res) => {
          that.pending = false
          if (res.success) {
            that.heightApproveLevelDia = false
          } else {
            that.$platform.notification({
              title: res.message,
              type: 'error'
            });
          }
        })
      }
    }
    window.addEventListener('message', onMessageCall);
    this.$once('hook:beforeDestroy', () =>  window.removeEventListener('message', onMessageCall))
  },
  methods: {
    getStatusList() {
      ProjectManage.getStatusList({projectTypeId: this.templateId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.statusList = res.data || []
      })
    },
    getTaskList() {
      ProjectManage.taskList({projectTypeId: this.templateId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.taskList = res.data || []
      })
    },
    async switchLevel(val) {
        this.iframeEditUrl = ''
        if (val === 4) {
          if (this.approveSetting?.appId && this.approveSetting?.formTemplateId)  {
            this.iframeEditUrl = `/paas/#/workflow?appId=${this.approveSetting.appId}&formId=${this.approveSetting.formTemplateId}&taskTypeId=${this.templateId}&moduleType=project`
            this.heightApproveLevelDia = true
            this.editloadingShow = true
          } else {
            let params = {
              templateId: this.templateId,
              processId: '',
            }
            await ProjectManage.approveSetting(params).then((res) => {
              if (res.success) {
                this.approveSetting = res.data
                this.iframeEditUrl = `/paas/#/workflow?appId=${this.approveSetting.appId}&formId=${this.approveSetting.formTemplateId}&taskTypeId=${this.templateId}&moduleType=project`
                this.heightApproveLevelDia = true
                this.editloadingShow = true
              }
            })
          }
      }
    },

    savePaasResult() {
      this.pending = true
      let iframe = this.$refs.iframePageEdit.contentWindow;
      let message = {
        action: 'shb.frame.getPaaSWorkflow',
        compId: this.compId,
      };
      iframe.postMessage(message, '*')
    },
    async openDialog(defaultForm, isEdit) {
      await this.getStatusList()
      await this.getTaskList()

      this.approveSetting  = {} // 先清空
      this.isFormEdit = isEdit
      if (defaultForm) {
        this.$set(this, 'form', _.cloneDeep(defaultForm))
      } else {
        this.$set(this, 'form', {})
        this.$set(this.form, 'approveSetting', {})
        this.$set(this.form, 'approveType', 1) // 默认是无需审批
      }
      // 高级审批条件配置
      this.approveSetting = _.cloneDeep(this.form.approveSetting)
      this.$refs['flowForm'].resetFields();

      this.isShow = true
    },
    // 关闭弹窗
    closeDialog() {
      // 把审批数据清空
      this.approveSetting = {}
      this.isShow = false
    },
    submitForm() {
      this.pedding = true
      this.$refs['flowForm'].validate((valid) => {
        if (valid) {
          this.pedding = false


          if (this.form.approveType === 4) {
            // 高级审批
            this.form = {
              ...this.form,
              approveSetting: this.approveSetting
            }
          } else {
            this.form = {
              ...this.form,
              approveSetting: {}, // 无需审批的时候，清除之前的数据
            }
          }
          
          this.$emit('submitForm', _.cloneDeep(this.form), this.isFormEdit)
        } else {
          this.pedding = false
          console.log('error submit!!');
          return false;
        }
      });
    }
  },
  computed: {
    statusListComput() {
      return (key) => {
        const curId = this.form[key];
        return (this.statusList || []).filter(v => v.id !== curId);
      }
    },
  },
  components: {
  },
}
</script>
<style lang="scss" scoped>
.paas-wrap {
  width: 100%;
  height: 100%;
}
</style>
<style lang="scss">

.approve-btn {
  margin-left: 10px;
  display: inline-block;
}
.add-form{
    padding: 20px;
    .form-step {
      display: flex;
      justify-content: center;
      font-size: 14px;
      text-align: center;
      margin-bottom: 20px;
      color: #595959;
      .step-item {
        padding: 0px 10px;
        height: 28px;
        line-height: 28px;
        border: 1px solid #E8E8E8;
        i {
          margin-right: 2px;
        }
        .start-state {
            color: #FF4D4F;
        }
        .target-state {
          color: #FF9100;
        }
      }
      .middle-line {
        width: 104px;
        height: 28px;
        line-height: 28px;
        margin: 0 4px;
        img {
          width: 94%;
        }
      }
      .item-middle {
        width: 66px;
        border: none;
      }
    }
    .w-100 {
      width: 100%;
    }
    ul.statecolor{
        padding: 0;
        line-height: 22px;
        display: flex;
        justify-content:space-between;
        li{
            list-style: none;
            display: inline-block;
            cursor: pointer;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            vertical-align: middle;
            position: relative;
            i{
                position: absolute;
                font-weight: bold;
                left: 50%;
                top: 50%;
                color: #fff;
                transform: translate(-50%, -50%);
            }
        }
    }
}
</style>